import sys
sys.path.append('./')
from Connection import Connection
from Config import *

class Db(Connection):
	
	# sqlListen 用来记录日志
	# alias连接指定的数据库服务器
	def __init__(self,alias=''):
		if not alias:
			alias = default['alias']

		db_config = databases[0][alias]
		Connection.__init__(self,
			db_config['ip'],
			db_config['user'],
			db_config['passwd'],
			db_config['database'],
			db_config['port']
		)



	#tableName 表名称	
	def table(self,tableName):
		self.tableName = tableName
		return self




	'''
		查询单条数据

		@return  单条结果集
	'''	
	def first(self):
		sql = 'select '+self.fields+' from '+self.tableName+self.wheres
		self.sqlListen = sql
		self.cursor.execute(sql)
		result = self.cursor.fetchone()
		return result

	


	'''
		查询多条数据
		@return  多条结果集
	'''	
	def get(self):
		sql = 'select '+self.fields+' from '+self.tableName+self.wheres+self.limits
		self.sqlListen = sql
		self.cursor.execute(sql)
		result = self.cursor.fetchall()
		return result	


	


	'''
		新增单条数据
		@return  多条结果集
	'''	
	def create(self,dictObj):
		
		key_str,key_value = self.insertParam(dictObj)

		sql = 'insert into '+self.tableName+'('+key_str+')values('+key_value+')'
		self.sqlListen = sql

		try:
		   # 执行sql语句
		   self.cursor.execute(sql)
		   #新增主键id
		   primary_id = self.db.insert_id()
		   # 提交到数据库执行
		   self.db.commit()
		   return primary_id
		except Exception as e:
		   # Rollback in case there is any error
		   self.db.rollback()
		   return e



	'''
		批量添加
		@return  primary_id 仅仅返回字典下标为0的主键id
	'''	
	def createAll(self,dictObjAll):
		
		key_str,key_value = self.insertParamAll(dictObjAll)


		sql = 'insert into '+self.tableName+'('+key_str+')values'+key_value
		self.sqlListen = sql
		try:
		   # 执行sql语句
		   self.cursor.execute(sql)
		   #新增主键id
		   primary_id = self.db.insert_id()
		   # 提交到数据库执行
		   self.db.commit()
		   return primary_id
		except Exception as e:
		   # Rollback in case there is any error
		   self.db.rollback()
		   return e







